import { nextTick, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import API from '@/api/goods'

/**
 * 获取商品详情
 * @param num 选择的数量
 * @return {{goods: null}}
 */
export default function useGoods(num) {
  // 出现路由地址商品Id发生变化, 但是不会重新初始化组件
  const goods = ref(null)
  const loading = ref(false)
  debugger
  const route = useRoute()  // 这时候为什么能访问到route ???

  watch(() => route.params.id, (newVal) => {
    if (newVal && `/product/${newVal}` === route.path) {
      loading.value = true
      API.getGoodsInfo(route.params.id)
        .then((res) => {
          // 动态路由组件之间切换, 组件不会重新加载, 以及使用子组件也不会重新加载
          // 让商品数据为null, 让使用v-if的组件可以重新销毁和创建,
          goods.value = null
          nextTick(() => {
            goods.value = res.result
            num.value = 1
            console.log(goods.value)
            loading.value = false
          })
        })
    }
  }, { immediate: true })

  return {
    goods,
    loading
  }
}
